<?php
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------
namespace app\staffapi\controller;

use app\model\car\CarInfo;
use app\Request;
use Darabonba\GatewaySpi\Models\InterceptorContext\response;
use think\facade\Db;
use think\exception\ValidateException;
use app\services\vendor\VendorServices;
use app\services\car\CarOrderServices;
use app\services\car\CarStaffService;
use com\junziqian\sdk\bean\req\sign\ApplySignReq;
use com\junziqian\sdk\bean\req\sign\ext\SignatoryReq;
use com\junziqian\sdk\util\Assert;
use com\junziqian\sdk\util\CommonUtil;
use com\junziqian\sdk\util\RequestUtils;
use crmeb\exceptions\AdminException;
use CURLFile;
use crmeb\exceptions\UploadException;
use app\services\other\UploadService;
use app\dao\system\attachment\SystemAttachmentDao;
use app\api\controller\v3\WxPayController;
use app\services\car\BaseLogServices;
use app\services\BaseServices;
use app\api\controller\v3\Wxpaymch;
class VendorController extends BaseServices
{
    private $serviceUrl;
    private $appkey ;
    private $appSecret;

    public function __construct(VendorServices $services){
        $this->services = $services;
        $this->serviceUrl = config('jzq')["jzq"]['Url'];
        $this->appkey = config('jzq')["jzq"]['App_Key'];
        $this->appSecret = config('jzq')["jzq"]['App_Secret'];
    }

    //商户入驻
    public function apply_vendor(Request $request)
    {
        $data = $request->postMore([
            ['name',''],
            ['phone',''],
        ]);
        $check = Db::name('vendor_apply')->where('phone',$data['phone'])->find();
        if($check){
            $data['updatetime'] = time();
            $insert = Db::name('vendor_apply')->where('id',$check['id'])->update($data);
        }else{
            $data['createtime'] = time();
            $insert = Db::name('vendor_apply')->insert($data);
        }
        if($insert){
            return app('json')->success("提交成功，请等待客服与您进行联系");
        }else{
            throw new ValidateException('提交失败');
        }
    }

    //商户自由注册/补充资料
    public function register_vendor(Request $request,VendorServices $services){
        $data = $request->postMore([
            ['id',''],
            ['name',''],
            ['city_id',''],
            ['title',''],
            ['short_desc',''],
            ['thumb',''],
            ['latlng',''],
            ['status',''],
            ['store_id','0'],
            ['contact_tel',''],
            ['before_min',''],
            ['cancel_min',''],
            ['cancel_rate',''],
            ['over_cancel_rate',''],
            ['start_time',''],
            ['end_time',''],
            ['place_fee',''],
            ['night_take_fee',''],
            ['night_return_fee',''],
            ['service_cost',''],
            ['oil_service_fee',''],
            ['charge_fee',''],
            ['place_type',''],
            ['place_hour',''],
            ['poiaddress',''],
            ['login_name',''],
            ['pwd',''],
            ['user_name',''],
            ['user_phone',''],
            ['is_person',''],
            ['sfz1',''],
            ['sfz2',''],
            ['qualification',''],
            ['sub_mchid','']
        ]);
        if($data['id']==0){
            if(!$data['city_id']) return app('json')->fail('请选择城市');
            if(!$data['name']) return app('json')->fail('请输入门店名称');
            if(!$data['contact_tel']) return app('json')->fail('请输入联系电话');

            if(!$data['login_name']) return app('json')->fail('请设置店员登录账号');
            if(!$data['user_name']) return app('json')->fail('请填写账户名称');
            if(!$data['pwd']) return app('json')->fail('请填写密码');
            if(!$data['user_phone']) return app('json')->fail('请填写店员手机号');
        }else{
            if(!$data['before_min']) return app('json')->fail('请选择最小预约时间');
            if(!$data['is_person']) return app('json')->fail('请选择个人/公司');
            if(!$data['sfz1']) return app('json')->fail('请上传身份证正面照');
            if(!$data['sfz2']) return app('json')->fail('请上传身份证反面照');
            if($data['is_person']==2){
                if(!$data['qualification']) return app('json')->fail('请上传资质照片');
            }
            if(!$data['start_time'] || !$data['end_time'] ) return app('json')->fail('请设置营业开始和结束时间');
        }
//        if($data['place_type'] == '0'){// 网点必填提示
//            if(!$data['service_cost']) return app('json')->fail('请输入手续费或车辆整备费');
//            if(!$data['place_fee']) return app('json')->fail('请输入跨网点还车每公里费');
//            if(!$data['night_take_fee'] || !$data['night_return_fee']) return app('json')->fail('夜间取车/还车费不能为空');
//            if(!$data['oil_service_fee'] || !$data['charge_fee']) return app('json')->fail('加油/充电服务费不能为空');
//            if(!$data['cancel_min'] || !$data['cancel_rate'] || !$data['over_cancel_rate']) return app('json')->fail('请完整选择取消规则内容');
//        }
        $this->services->add((int)$data['id'],$data);
        return app('json')->success('提交成功');
    }

    //查询补充资料or微信特约商户审核状态
    public function slect_bc_applyment(Request $request){
        $data =$request->getMore([
            ['id',''],
        ]);
        $is_complete = 1;//已完善
        $wx_applyment = 0;//0未提交1已提交（审核中）2已驳回 3待签约 4已完成
        $wx_applyment_list = Db::name('wx_applyment')->where(['uid'=>$data['id']])->find();
        if($wx_applyment_list){
            $wx = new Wxpaymch();
            $check = $wx->queryApplyment($wx_applyment_list['business_code']);//申请单号查询申请状态
            $audit_detail = "";//驳回原因
            $sign_url = "";//签约链接
            if($check['applyment_state']){
                switch ($check['applyment_state']) {
                    case "APPLYMENT_STATE_EDITTING":
                        $wx_applyment = "编辑中";
                        break;
                    case "APPLYMENT_STATE_AUDITING":
                        $wx_applyment = "审核中";
                        $sign_url = $check['sign_url'];
                        break;
                    case "APPLYMENT_STATE_REJECTED":
                        foreach($check['audit_detail'] as $k=>$v){
                            $audit_detail =$audit_detail."驳回原因"."[".$k."]".$v['reject_reason'];
                        }
                        $wx_applyment = "已驳回";
                        break;
                    case "APPLYMENT_STATE_TO_BE_CONFIRMED":
                        $wx_applyment = "待账户验证";
                        $sign_url = $check['sign_url'];
                        break;
                    case "APPLYMENT_STATE_TO_BE_SIGNED":
                        $wx_applyment = "待签约";
                        $sign_url = $check['sign_url'];
                        break;
                    case "APPLYMENT_STATE_SIGNING":
                        $wx_applyment = "开通权限中";
                        break;
                    case "APPLYMENT_STATE_FINISHED":
                        $wx_applyment = "已完成";
                        break;
                    case "APPLYMENT_STATE_CANCELED":
                        $wx_applyment = "已作废";
                        $wx_applyment = 0;
                        break;
                    default:
                        // 如果没有匹配的值
                }
            }
            $update = Db::name('wx_applyment')->where('id',$wx_applyment_list['id'])->update(['audit_detail'=>$audit_detail,'applyment_state'=>$wx_applyment]);
            $list['is_complete'] = $is_complete;
            $list['wx_applyment'] = $wx_applyment;
            $list['audit_detail'] = $audit_detail;
            $list['sign_url'] = $sign_url;
        }else{
            $wx_applyment = 0;//0未提交1已提交（审核中）2已驳回 3待签约 4已完成
            $list['is_complete'] = $is_complete;
            $list['wx_applyment'] = $wx_applyment;
            $list['audit_detail'] = "";
            $list['sign_url'] = "";
        }
        $list['self'] = 2;

        return app('json')->success($list);

    }

    //查看进件资料、用于申请驳回后，用户重新提交
    public function get_applyment(Request $request){
        $data =$request->getMore([
            ['id',''],
        ]);
        $wx_applyment_list = Db::name('wx_applyment')->where(['uid'=>$data['id']])->find();
        if(!$wx_applyment_list) return app('json')->fail('数据异常！');
        $wx_applyment_list['contact_info'] = json_decode($wx_applyment_list['contact_info'],true);
        $wx_applyment_list['subject_info'] = json_decode($wx_applyment_list['subject_info'],true);
        $wx_applyment_list['business_info'] = json_decode($wx_applyment_list['business_info'],true);
        $wx_applyment_list['bank_account_info'] = json_decode($wx_applyment_list['bank_account_info'],true);
        return app('json')->success($wx_applyment_list);

    }

    //查看微信图片id
    public function get_applyment_img(Request $request){
        $data =$request->getMore([
            ['media_id',''],
        ]);
        $wx_img = Db::name('wx_img_log')->field('img')->where('media_id',$data['media_id'])->find();
        if(!$wx_img) return app('json')->fail('图片不存在！');
        return app('json')->success($wx_img);
//        echo"<img src=$wx_img border=0 />";
    }
    //获取商家首页信息 订单总数+理赔信息+车辆总数 +车辆列表
    public function get_home(Request $request){

        $page = input("page","1","intval");
        $manager =  $request->managerInfo();
        $place_id = $manager['place_id'];
        $keywors = input('keywors','');
        $where = [];
        if($keywors){
            $where[] = ['a.car_no|bb.brand_name|ti.type_name','like','%'.$keywors.'%'];
        }
        //获取订单总数
        $order = Db::name('car_order')->where(['is_del'=>0,'store_id'=>$place_id])->where('status','<>',0)->count();
        //理赔
        $lipei = Db::name('car_wz')->where('status',1)->where('store_id',$place_id)->count();
        //车辆总数
        $size = 100;
        $subQuery = Db::name('car_info')
            ->alias('i')
            ->leftJoin('car_type t', 'i.type_id=t.id')
            ->leftJoin('car_type_info ti','t.type_info_id=ti.id')
            ->leftJoin('car_brand bb','bb.id=ti.brand_id')
            ->where('i.is_del', 0)
            ->where('t.place_id', $place_id)
            ->field('i.id, i.insurance_date,ti.pic,ti.type_name,ti.gear,ti.seat_num,ti.power,bb.brand_name')
            ->buildSql();
        $list = Db::name('car_info')
            ->alias('a')
            ->rightJoin([$subQuery => 'b'], 'a.id=b.id')
            ->leftJoin('car_type t', 'a.type_id=t.id')
            ->leftJoin('car_type_info ti','t.type_info_id=ti.id')
            ->leftJoin('car_brand bb','bb.id=ti.brand_id')
            ->field('a.id, b.insurance_date,b.pic,ti.type_name,b.gear,b.seat_num,b.power,a.insurance_date,a.car_no,ti.oil_box,t.price,a.car_status,a.sxj_status,bb.brand_name,a.img')
            ->limit((($page - 1) * $size),$size)
            ->where($where)
            ->select()->toArray();
        $car_num = count($list);
        foreach ($list as &$item){
            $item['insurance_date'] = $item['insurance_date'] ? date('Y-m-d',$item['insurance_date']) : '暂无';
            $item['gear'] = $item['gear'] == 'auto' ? '自动挡' : '手动挡';
            if($item['img']){
                $item['img'] = json_decode($item['img'],true);
                $item['pic'] = $item['img'][0];
            }
        }
        $res['order_num'] = $order;
        $res['lipei_num'] = $lipei;
        $res['car_num'] = $car_num;
        $res['list'] = $list;
        $res["page"]=$page;
        $res["total"]=$car_num;
        $res["size"]=$size;
        return app('json')->success($res);
    }
    /**
     * 地点详细
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getPlaceInfo(Request $request){
        $data =$request->getMore([
            ['id',''],
        ]);
        if(!$data['id']) return app('json')->fail('缺少参数');
        return app('json')->success($this->services->getInfo((int)$data['id']));
    }

    //商家添加店铺车型
    public function vendor_add_car(Request $request,VendorServices $services){
        $manager =  $request->managerInfo();
         $place_id = $manager['place_id'];
        //车型信息
        $data = $request->postMore([
            ['car_id', 0],
            ['type_info_id', ''],//车型id
            ['place_id', $place_id],//所属门店
//            ['price_hour', ''],
            ['price', ''],
            ['sat_price', ''],
            ['sun_price', ''],
            ['base_service_fee', ''],
            ['illegal_deposit', ''],
            ['deposit', ''],
            ['status', 1],
            ['zhoumo_price', ''],
        ]);
        //车辆信息
        $data2 = $request->postMore([
            ['car_no', ''],
            ['run_km', ''],
            ['upkeep_km', ''],
            ['upkeep_day', ''],
            ['last_upkeep_date', ''],
            ['last_upkeep_km', ''],
            ['check_date', ''],
            ['insurance_date', ''],
            ['commercial_insurance_date', ''],
            ['type_id', $data["type_info_id"]],//车型信息
            ['status', 1],
            ['img', ''],
//            ['jiazhao_grade', ''],
//            ['bed', ''],
//            ['fuel', ''],
//            ['function', ''],
//            ['chang', ''],
//            ['kuan', ''],
//            ['gao', ''],
        ]);
        if(!$data['type_info_id']) return app('json')->fail('请选择车型');
//        if(!$data['price_hour']) return app('json')->fail('请输入小时价格');
        if(!$data['price']) return app('json')->fail('请输入价格/天');
//        if(!$data['sat_price']) return app('json')->fail('请输入周六价格/天');
//        if(!$data['sun_price']) return app('json')->fail('请输入周日价格/天');
        if(!$data['zhoumo_price']) return app('json')->fail('请输入周末价格/天');
        if(!$data['base_service_fee']) return app('json')->fail('请输入基础服务费');
        if(!$data['illegal_deposit']) return app('json')->fail('请输入违章押金');
        if(!$data['deposit']) return app('json')->fail('请输入车型押金');
        if(!$data2['car_no']) return app('json')->fail('请输入车牌号');
        if(!$data2['type_id']) return app('json')->fail('请选择车型');
        $data['sat_price'] = $data["zhoumo_price"];
        $data['sun_price'] = $data["zhoumo_price"];
        $services->save_type((int)$data['car_id'], $data,$data2);
        return app('json')->success('提交成功');
    }


    //门店下拉列表
    public function getStoreList(){
        $list = Db::name('base_place')
            ->field('id as value,title as label')
            ->where(['is_del'=>0,'store_id'=>0])
            ->select()->toArray();
        return app('json')->success($list);
    }

    //车型下拉列表
    public function getTypeInfoSelect(){
        $list = Db::name('car_type_info')->where(['is_del'=>0])->select()->toArray();
        $typeInfo = [];
        foreach ($list as $item){
            $typeInfo[] = ['value'=>$item['id'],'label'=>$item['type_name']];
        }
        return app('json')->success($typeInfo);
    }

    //管理车辆列表
    public function get_vendor_car_list(Request $request){
        $page = input("page","1","intval");
        $status = input("car_status",'');
        $where = [];
        if($status||$status=='0'){
            $where['car_status'] = $status;
        }
        $manager =  $request->managerInfo();
        $place_id = $manager['place_id'];
        $size = 100;
        $subQuery = Db::name('car_info')
            ->alias('i')
            ->leftJoin('car_type t', 'i.type_id=t.id')
            ->leftJoin('car_type_info ti','t.type_info_id=ti.id')
            ->where('i.is_del', 0)
            ->where('t.place_id', $place_id)
            ->field('i.id, i.insurance_date,ti.pic,ti.type_name,ti.gear,ti.seat_num,ti.power')
            ->buildSql();
        $list = Db::name('car_info')
            ->alias('a')
            ->rightJoin([$subQuery => 'b'], 'a.id=b.id')
            ->leftJoin('car_type t', 'a.type_id=t.id')
            ->leftJoin('car_type_info ti','t.type_info_id=ti.id')
            ->field('a.id, b.insurance_date,b.pic,b.type_name,b.gear,b.seat_num,b.power,a.insurance_date,a.car_no,ti.oil_box,t.price,a.car_status,a.sxj_status')
            ->where($where)
            ->limit((($page - 1) * $size),$size)
            ->select()->toArray();
        $car_num = count($list);
        foreach ($list as &$item){
            $item['insurance_date'] = $item['insurance_date'] ? date('Y-m-d',$item['insurance_date']) : '暂无';
            $item['gear'] = $item['gear'] == 'auto' ? '自动挡' : '手动挡';
        }
        $res['list'] = $list;
        $res["page"]=$page;
        $res["total"]=$car_num;
        $res["size"]=$size;
        return app('json')->success($res);
    }

    //车辆详情
    public function get_vendor_car_info(Request $request,VendorServices $services){
        $data = $request->getMore([
            ['car_id','']
        ]);
        return app('json')->success($services->getCarDetail((int)$data['car_id']));
    }



    //上下架车辆
    public function sjx_car(Request $request){
        $manager =  $request->managerInfo();
        $place_id = $manager['place_id'];
        $data = $request->getMore([
            ['id',''],
            ['status','']
        ]);
        if (!$data['id']) return app('json')->fail('参数错误');
        return app('json')->success($this->services->upanddowncar((int)$data['id'],(int)$data['status'],$place_id));
    }

    //删除车辆
    public function del_car(Request $request){
        $data = $request->getMore([
            ['id','']
        ]);
        if (!$data['id']) return app('json')->fail('参数错误');
        return app('json')->success($this->services->delInfo((int)$data['id']));
    }

    //检查当前账号是否有签约数据
    public function checkSgin(Request $request,CarStaffService $service){
        $manager =  $request->managerInfo();
        $place_id = $manager['id'];
        return app('json')->success($this->services->checkStaffInfo($place_id));
    }

    //上传图片接口（未使用）
    public function update_sign_img(int $pid, string $file, int $upload_type, int $type, $menuName){
        $realName = false;
        if ($upload_type == 0) {
            $upload_type = sys_config('upload_type', 1);

        }
        if ($menuName == 'weixin_ckeck_file' || $menuName == 'ico_path') {
            $upload_type = 1;
            $realName = true;
        }
        try {
            $path = make_path('attach', 2, true);
            $upload = UploadService::init($upload_type,1);
            $res = $upload->to($path)->validate()->move($file, $realName);
            if ($res === false) {
                throw new UploadException($upload->getError());
            } else {
                $fileInfo = $upload->getUploadInfo();
                $fileType = pathinfo($fileInfo['name'], PATHINFO_EXTENSION);
                if ($fileInfo && $type == 0 && !in_array($fileType, ['xlsx', 'xls', 'mp4'])) {
                    $data['name'] = $fileInfo['name'];
                    $data['real_name'] = $fileInfo['real_name'];
                    $data['att_dir'] = $fileInfo['dir'];
                    $data['satt_dir'] = $fileInfo['thumb_path'];
                    $data['att_size'] = $fileInfo['size'];
                    $data['att_type'] = $fileInfo['type'];
                    $data['image_type'] = $upload_type;
                    $data['module_type'] = 1;
                    $data['time'] = $fileInfo['time'] ?? time();
                    $data['pid'] = $pid;
                    $SystemAttachmentDao = new SystemAttachmentDao();
                    $SystemAttachmentDao->save($data);
                }
                return $res->filePath;
            }
        } catch (\Exception $e) {
            throw new UploadException($e->getMessage());
        }
    }

    //君子签个人自定义签名图片
    public function uploadPersSign(Request $request){
        $id = input("id","");
        $img = input("img","");
        if (!$id) return app('json')->fail('id为空');
        if (!$img) return app('json')->fail('签名图片为空');
        $data = Db::name('contract_entry')->where('id',$id)->find();
        if (!$data) return app('json')->fail('合同数据为空');
        $public_path = public_path();//获取public绝对路径
//        //上传图片
//        $upload_type = 1;
//        $type = 0;
//        [$pid, $file, $menuName] = $request->postMore([
//            ['pid', 7],
//            ['file', 'file'],
//            ['menu_name', '']
//        ], true);
//        $res = $this->update_sign_img((int)$pid, $file, $upload_type, $type, $menuName);
        $v = $public_path.$img;

        //构建请求工具
        $requestUtils=new RequestUtils($this->serviceUrl, $this->appkey, $this->appSecret);
        //初始化合同参数
        $request=array(
            "identityCard" => $data["shenfenz"], //TODO 身份证
            "signImgFile" => new CURLFile($v,null,"test.png"),//php5.3-php5.6请使用@.方式
        );

        $response=$requestUtils->doPost("/v2/user/uploadPersSign",$request);
        if($response->success==1){
            return app('json')->success("签名成功");
        }else{
            throw new ValidateException($response->msg);
        }
    }

    //用户签约
    public function jzq_user(){
        $id = input("id","");
        if (!$id) return app('json')->fail('id为空');
        $data = Db::name('contract_entry')->where('id',$id)->find();
        if (!$data) return app('json')->fail('合同数据为空');

        $arr= [
            'a_stampname'=>$data['Jdaibiao'],
            'a_stampphone'=>$data['Jdbphone'],
            'b_company'=>$data['Yname'],
            'b_taxid'=>$data['Taxpayer'],
            'b_addr'=>$data['Address'],
            'b_username'=>$data['Yname'],
            'b_userphone'=>$data['Yphone'],
            'b_motorhomes'=>$data['Ycar'],//车辆信息
            'startdate'=>$data['Startdate'],
            'enddate'=>$data['Enddate'],
            'manageprice'=>$data['Deposit'],//押金
            'klchbankname'=>$data['Bankname'],//开户名称
            'klchbank'=>$data['Bank'],//开户行
            'klchcard'=>$data['Account'],//银行账户
            'b_stampphone'=>$data['Yphone'],//乙方手机号
        ];
        $arr['startdate'] = date("Y年m月d日",$data['Startdate']);//开始日期
        $arr['enddate'] = date("Y年m月d日",$data['Enddate']);//结束日期
        $arr['createdate'] = date("Y年m月d日",time());//创建日期
        //构建请求工具
        $requestUtils=new RequestUtils($this->serviceUrl, $this->appkey, $this->appSecret);
        //CURLFile 可以传url或filePath，但必须保证文件存在且有效，否则php不会报错，只会导致http请求返回null（并没有调到服务端）。
        ////初始化合同参数
        $request=new ApplySignReq();


        $request->contractName=$data["Name"]."房车入驻合同";
        $request->serverCa=1;//使用云证书
        $request->fileType = 2;
        $request->templateNo="C005";//模版编号
        $request->positionType=2;//指定公章位置
        $request->templateParams=$arr; //模版变量,可以传array或json_string
        $request->dealType = 1;////处理方式:为空或0时默认为手签合同(用户有感知);1自动签约(用户无感知);2只保全;5部份自动签;6HAS


        $sReq=new SignatoryReq();
        //signatories字段说明
        $sReq->fullName=$data['Name'];//签约方名称,不超过50个字符
        $sReq->identityType=1;//身份类型:1身份证,2护照,3台胞证,4港澳居民来往内地通行证,11营业执照,12统一社会信用代码
        $sReq->identityCard=$data["shenfenz"];//个人传身份证号，企业传营业执照号/统一社会信用代码号
        $sReq->mobile=$data["Tel"];//手机号码（个人必传），11个字符
        $sReq->orderNum=2;//签字顺序:连续签（orderNum只是针对于当前合同,对批量签多个合同顺序不能指定）,顺序签时必传,[0,100)
        $sReq->searchKey='---------------------.--';//签字位置-按关键字签署，positionType=2时必须传入，关键字支持多个;以英文;分隔
        $sReq->authlevel=[13];//验证等级(传数组字符串)例:[2,10];2 银行卡四要素认证； 10 银行卡三要素认证； 11 人脸识别；12 短信验证码 ；13 运营商三要素认证
        $sReq->signLevel=2;//签字类型，标准图形章或公章:0标准图形章,1公章或手写,2公章手写或手写,3个人方形标准章（用户类型是个人且姓名2-4个字符生效，其他情况默认使用系统标准图形章）
        $request->signatories=array($sReq);
        //signatories字段说明

        //发起PING请求
        $response=$requestUtils->doPost("/v2/sign/applySign",$request);
        if($response->success==1) {
            $update = Db::name('contract_entry')->where('id',$data['id'])->update(['Contractnumber'=>$response->data,'Sign_status'=>2]);//更新合同编号到数据库里
        }else{
            return app('json')->fail('签署失败!失败原因：'.$response->msg);
        }
        return app('json')->success("签署成功！");


    }

    //获取店铺基本信息
    public function get_shop(Request $request){
        $manager =  $request->managerInfo();
        $place_id = $manager['place_id'];
        $place = Db::name('base_place')->where('id',$place_id)->find();
        if (!$place) return app('json')->fail('没有店铺信息！');
        return app('json')->success($place);
    }

    //查询合同列表
    public function get_hetong_list(Request $request){
        $manager =  $request->managerInfo();
        $id = $manager['id'];
        $ht = Db::name('contract_entry')->where('Uid',$id)->select()->toArray();
        return app('json')->success($ht);
    }

    //修改头像
    public function up_face(Request $request){
        $face = input('face');
        if (!$face) return app('json')->fail('请上传头像！');
        $manager =  $request->managerInfo();
        $id = $manager['id'];
        $staff = Db::name('car_staff')->where('id',$id)->find();
        if (!$staff) return app('json')->fail('没有账号信息！');
        Db::name('car_staff')->where('id',$id)->update(['face'=>$face]);
        return app('json')->success('头像修改成功');
    }

    //获取店员基础信息
    public function staffinfo(Request $request){
        $manager =  $request->managerInfo();
        $id = $manager['id'];
        $staff = Db::name('car_staff')->where('id',$id)->find();
        if (!$staff) return app('json')->fail('没有账号信息！');
        return app('json')->success($staff);
    }

    //查看君子签合同
    public function get_linkAnonyDetail(){
        $id = input("id","");
        if (!$id) return app('json')->fail('id为空');
        $data = Db::name('contract_entry')->where('id',$id)->find();
        if (!$data) return app('json')->fail('合同数据为空');
        //构建请求工具
        $requestUtils=new RequestUtils($this->serviceUrl, $this->appkey, $this->appSecret);
        //初始化合同参数
        $request=array(
            "applyNo" => $data['Contractnumber'], //TODO *
//            "fullName" => $data['Name'], //TODO *
//            "identityCard" => $data['shenfenz'], //TODO *
//            "identityType" => 1, //TODO *
        );
        $response=$requestUtils->doPost("/v2/sign/linkAnonyDetail",$request);
        if($response->success==1) {
            return app('json')->success($response->data);
        }else{
            return app('json')->fail('查询失败');
        }
    }

    //添加违章信息
    public function add_wzinfo(Request $request){
        $data = $request->postMore([
            ['order_id',''],
            ['illegal_return_type','3'],
            ['wz_img_array',''],
            ['illegal_remark',''],
            ['amount','0'],
        ]);
        if($data['amount']<0)return app('json')->fail('填写违章金额不可以小于0！');
        if(!$data['order_id']) return app('json')->fail('订单id错误');
        if(!$data['illegal_remark']) return app('json')->fail('请添加用户违章说明');
        $car_order = Db::name('car_order')->where('id',$data['order_id'])->find();
        if(!$car_order) return app('json')->fail('订单不存在');

        $list = [
            'order_id'=>$data["order_id"],
            'illegal_return_type'=>3,
            'illegal_remark'=>$data['illegal_remark'],
            'wz_sub_time'=>time(),
            'wz_img_array' => $data["wz_img_array"],
            'uid'=>$car_order['uid'],
            'store_id'=>$car_order['store_id'],
            'status'=>1,
            'amount'=>$data['amount']
        ];
        $insert = Db::name('car_wz')->insert($list);
        return app('json')->success("提交违章信息成功");
    }

    //填写违章信息时查询该条订单违章金额总和是否超过押金
    public function check_wzyajin(Request $request){
        $data = $request->postMore([
            ['order_id',''],
        ]);
        if(!$data['order_id']) return app('json')->fail('订单id错误');
        $car_order = Db::name('car_order')->where('id',$data['order_id'])->find();
        if(!$car_order) return app('json')->fail('订单不存在');
        $sum_amount = Db::name('car_wz')->where('order_id',$data['order_id'])->where(['illegal_return_type'=>3,'status'=>1])->sum('amount');
        $sum_amount = bcsub($car_order['illegal_deposit'],$sum_amount,2);
        return app('json')->success("成功",['sum_amount'=>$sum_amount]);

    }

    //违章列表
    public function get_wzlist(Request $request){
        $manager =  $request->managerInfo();
        $page = input("page","1","intval");
        $size = 10;
        $name = input("name",'');
        $status = input("status",'');
        $order_id = input('order_id','');
        $where = [];
        if($name){
            $where[] = ['o.contact_name','like','%'.$name.'%'];
        }
        if($status||$status==0&&$status!=""){
            $where[] = ['r.status','=',$status];
            if($status==1){
                $where[] = ['r.illegal_return_type','=',3];
            }elseif($status==2){
                $where[] = ['r.illegal_return_type','in','1,2'];
            }
        }
        if($order_id){
            $where[] = ['order_id','=',$order_id];
        }
        $manager =  $request->managerInfo();
        $id = $manager['place_id'];
        $car_order = Db::name('car_wz')
            ->alias('r')
            ->join('car_order o','r.order_id=o.id','left')
            ->join('car_order_take t','t.id=o.take_id','left')
            ->join('base_place p','p.id=r.store_id','left')
            ->field('r.illegal_remark,r.id,o.order_no,r.wz_img_array,r.wz_sub_time,r.status,o.contact_name,o.contact_mobile,t.car_no,t.car_id,o.type_name,r.wz_ok_time,p.contact_tel,o.return_id,r.amount')
            ->where('o.store_id',$id)
            ->where($where)
            ->order('r.id desc')
            ->limit((($page - 1) * $size),$size)
            ->select()->toArray();

        foreach($car_order as $k=>$v){
            if($v['return_id']){
                $car_order_return = Db::name('car_order_return')->where('id',$v['return_id'])->find();
                if($car_order_return){
                    $time = $car_order_return['add_time']+1296000;
                    $countdown = $time - time();
                    $countdown = floor($countdown/86400);
                    $car_order[$k]['countdown'] = $countdown."天";
                    if($countdown<0){
                        $car_order[$k]['countdown'] ="";
                    }
                    $car_order[$k]['wz_sub_time'] = date('Y-m-d H:i:s',$v['wz_sub_time']);
                }
            }else{
                $car_order[$k]['countdown']="";
            }
        }
        $car_num = count($car_order);
        $res['list'] = $car_order;
        $res["page"]=$page;
        $res["total"]=$car_num;
        $res["size"]=$size;
        return app('json')->success($res);
    }

    //违章详情
    public function wz_info(Request $request){
        $data = $request->getMore([
            ['id','']
        ]);
        if(!$data['id']) return app('json')->fail('id为null');
        $info = Db::name('car_wz')
            ->alias('r')
            ->join('car_order o','r.order_id=o.id','left')
            ->join('car_order_take t','t.id=o.take_id','left')
            ->join('base_place p','p.id=r.store_id','left')
            ->field('r.illegal_remark,r.id,o.order_no,r.wz_img_array,r.wz_sub_time,r.status,o.contact_name,o.contact_mobile,t.car_no,t.car_id,o.type_name,r.wz_ok_time,p.contact_tel,o.return_id,r.amount')
            ->where('r.id',$data['id'])
            ->find();
        if(!$info) return app('json')->fail('违章信息不存在');
        if($info['return_id']){
                $car_order_return = Db::name('car_order_return')->where('id',$info['return_id'])->find();
                if($car_order_return){
                    $time = $car_order_return['add_time']+1296000;
                    $countdown = $time - time();
                    $countdown = floor($countdown/86400);
                    $info['countdown'] = $countdown."天";
                    if($countdown<0){
                        $info['countdown'] = "";
                    }

                }
            }else{
            $info['countdown'] = "";
        }
        $info['wz_sub_time'] = date('Y-m-d H:i:s',$info['wz_sub_time']);
        $info['wz_img_array'] = json_decode($info['wz_img_array'],true);
        return app('json')->success($info);
    }

    //查询当前可申请理赔的订单
    public function get_claimable_order(Request $request){
        $car_no = input("car_no",'');
        $where = [];
        if($car_no){
            $where[] = ['t.car_no','like','%'.$car_no.'%'];
        }
        $manager =  $request->managerInfo();
        $id = $manager['place_id'];
        $order = Db::name('car_order')
            ->alias('o')
            ->field('o.id,o.uid,o.type_id,o.type_name,o.type_pic,o.contact_name,o.contact_mobile,o.status,o.start_time,o.end_time,t.car_no')
            ->join('car_order_take t','t.id=o.take_id','left')
            ->where('store_id',$id)
            ->where('status','in','20,30')
            ->where($where)
            ->order('o.id desc')
            ->select()->toArray();
        return app('json')->success($order);
    }

    //撤销违章信息。（已完成理赔）
    public function ok_claim(Request $request){
        $data = $request->getMore([
            ['id',''],
        ]);
        if (!$data['id']) return app('json')->fail('参数错误');
        $info = Db::name('car_wz')->where('id',$data['id'])->find();
        if (!$info) return app('json')->fail('理赔信息不存在');
        $orderInfo = Db::name('car_order')->where('id',$info["order_id"])->find();
        if (!$orderInfo) return app('json')->fail('理赔订单不存在');
        $staffInfo = $request->managerInfo();
        // 启动事务
        Db::startTrans();
        try {
          Db::name('car_wz')->where('id',$data['id'])->update(['status'=>2,'wz_ok_time'=>time(),'illegal_return_type'=>1]);
            //完成还车直接退还用户违章押金
//            $tui_fee = $orderInfo['illegal_deposit']*100;//违章押金
//            $totalFee = $orderInfo['price']*100;//订单总金额
//            $out_refund_no = "illegal_deposit".$orderInfo['order_no'];//系统内部退款订单号，这里用deposit标识是车辆押金加上订单号
//            $data = Db::name('car_wz')->where('id',$data['id'])->update(['status'=>2,'wz_ok_time'=>time(),'illegal_return_type'=>1]);
//            //查询该订单有多少条未处理的违章
//            $w_wz = Db::name('car_wz')->where('order_id',$orderInfo['id'])->where(['status'=>1])->count();
//            if($w_wz==0)
//            {
//                $wxpay = new WxPayController();
//                $ok2 = $wxpay->wx_refund($orderInfo['out_trade_no'],0,$totalFee,$tui_fee,0,0,0,$out_refund_no);
//                if($ok2['code']==1){
//                    Db::name('car_order')->where('id',$orderInfo['id'])->update(['it_illegal_deposit'=>1,'status'=>40]);
//                    $tui_fee = $tui_fee/100;
//                    $msg = $orderInfo['order_no'].'订单用户进行还车，退违章押金'.$tui_fee."元";
//                    BaseLogServices::addLog($orderInfo['id'],2,$msg,2,$staffInfo['id'],$staffInfo['user_name'],28);
//                }
//            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            return app('json')->fail($e->getMessage());
            // 回滚事务
//            Db::rollback();
        }
        return app('json')->success("本条违章已处理完成！");
    }

    //获取城市信息
    public function get_city(){
        $base_city = Db::name('base_city')->where('is_del',0)->select()->toArray();
        return app('json')->success($base_city);
    }

        /*
    * 资金流水
    * 2024年3月4日10:50:29
    * */
    public function fundFlow(Request $request){
        $where = $request->getMore([
            ['start_time', ''],
            ['end_time', ''],
            ['order_no', ''],
            ['limit', 10],
            ['page', 1],
            ['type', ''],
            ['phone', ''],
            ['name', ''],
        ]);
        $manager =  $request->managerInfo();
        $id = $manager['place_id'];
        $page = $where['page'];
        $where2 = [];
        if(!empty($where['start_time']) && !empty($where['end_time']) ){
            $where2[] = ["f.add_time",">=",$where['start_time']];
            $where2[] = ["f.add_time","<=",$where['end_time']];
        }
        if(!empty($where['type'])){
            $where2[] = ["f.type","=",$where['type']];
        }
        if(!empty($where['order_no'])){
            $where2[] = ["o.order_no","like","%".$where['order_no']."%"];
        }
        if(!empty($where['phone'])){
            $where2[] = ["o.contact_mobile","like","%".$where['phone']."%"];
        }
        if(!empty($where['name'])){
            $where2[] = ["o.contact_name","like",'%'.$where['name'].'%'];
        }
        $where2[] = ["f.store_id","=",$id];

        $size = $where['limit'];
        $data = Db::name('order_flow')
            ->alias('f')
            ->field('f.remarks,f.id as f_id,f.order_id as f_order_id,f.type as f_type,f.amount as f_amount,f.add_time as f_add_time,f.account as f_account,o.illegal_deposit,o.deposit,o.shifu_car_fee,o.coupon_price,o.order_no,o.pay_time,o.type_name,o.contact_name,
            o.contact_mobile,o.add_time,o.start_time,o.end_time,p.title as store_name,o.pay_time,o.price,t.car_no,o.book_day as tianshu')
            ->limit((($page - 1) * $size),$size)->order('f.id desc')
            ->join('car_order o','f.order_id = o.id','left')
            ->join('car_order_take t','t.id=o.take_id','left')
            ->join('base_place p','p.id=o.store_id','left')
            ->order('f_add_time','desc')
            ->where($where2)
            ->select()->toArray();
        foreach ($data as $k=>$v) {
            $data[$k]['add_time'] = $v['add_time'] ? date('Y年m月d日 H时i分', $v['add_time']) : '暂无';
            $data[$k]['pay_status'] = $v['pay_time'] ? '已支付' : '未支付';
            $data[$k]['start_time'] = $v['start_time'] ? date('m月d日 H时i分', $v['start_time']) : '暂无';
            $data[$k]['end_time'] = $v['end_time'] ? date('m月d日 H时i分', $v['end_time']) : '暂无';
            $data[$k]['time'] = date('m月d日 H时i分', $v['start_time']);
            $data[$k]['time2'] = date('m月d日 H时i分', $v['end_time']);
            $data[$k]['f_add_time'] = $v['f_add_time'] ? date('Y年m月d日 H时i分s秒', $v['f_add_time']) : '暂无';
            $data[$k]['pay_time'] = $v['pay_time'] ? date('Y年m月d日 H时i分s秒', $v['pay_time']) : '暂无';
            if($v['f_type']==1){
                $data[$k]['f_typename'] = '订单款';
            }elseif($v['f_type']==21){
                $data[$k]['f_typename'] = '还车退款';
            }elseif($v['f_type']==31){
                $data[$k]['f_typename'] = '违章押金退款';
            }elseif($v['f_type']==2){
                $data[$k]['f_typename'] = '车辆押金';
            }elseif($v['f_type']==3){
                $data[$k]['f_typename'] = '违章押金';
            }elseif($v['f_type']==4){
                $data[$k]['f_typename'] = '分账款';
            }elseif($v['f_type']==5){
                $data[$k]['f_typename'] = '续租款';
            }elseif($v['f_type']==6){
                $data[$k]['f_typename'] = '服务费';
            }elseif($v['f_type']==11){
                $data[$k]['f_typename'] = '订单退款';
            }elseif($v['f_type']==41){
                $data[$k]['f_typename'] = '分账退款';
            }else{
                $data[$k]['f_typename'] = '取消订单退款';
            }
        }

        $data2 = Db::name('order_flow')
            ->alias('f')
            ->field('f.remarks,f.id as f_id,f.order_id as f_order_id,f.type as f_type,f.amount as f_amount,f.add_time as f_add_time,f.account as f_account,o.illegal_deposit,o.deposit,o.shifu_car_fee,o.coupon_price,o.order_no,o.pay_time,o.type_name,o.contact_name,
            o.contact_mobile,o.add_time,o.start_time,o.end_time,p.title as store_name,o.pay_time,o.price,t.car_no,o.book_day as tianshu')
            ->join('car_order o','f.order_id = o.id','left')
            ->join('car_order_take t','t.id=o.take_id','left')
            ->join('base_place p','p.id=o.store_id','left')
            ->where($where2)
            ->select()->toArray();
        $res = [];
        $res['list'] = $data;
        $res["page"]=$where['page'];
        $res["count"]=count($data2);
        $res["size"]=$size;
        return app('json')->success($res);
    }
}
